

package com.maoshi.shop.user.api.listener;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.maoshi.shop.bean.app.dto.ShopCartOrderMergerDto;
import com.maoshi.shop.bean.enums.ScoreLogType;
import com.maoshi.shop.bean.event.SubmitScoreOrderEvent;
import com.maoshi.shop.bean.model.*;
import com.maoshi.shop.bean.order.SubmitOrderOrder;
import com.maoshi.shop.common.exception.MaoshiShopBindException;
import com.maoshi.shop.security.api.util.SecurityUtils;
import com.maoshi.shop.service.UserExtensionService;
import com.maoshi.shop.user.comment.model.UserScoreLog;
import com.maoshi.shop.user.comment.service.UserScoreLogService;
import lombok.AllArgsConstructor;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 确认订单信息时的用户积分操作
 *
 * @author LGH
 */
@Component("userSubmitOrderListener")
@AllArgsConstructor
public class SubmitOrderListener {

    private final UserExtensionService userExtensionService;
    private final UserScoreLogService userScoreLogService;

    /**
     * 计算订单金额
     */
    @EventListener(SubmitScoreOrderEvent.class)
    @Order(SubmitOrderOrder.USER)
    public void userSubmitOrderListener(SubmitScoreOrderEvent event) {
        ShopCartOrderMergerDto mergerOrder = event.getMergerOrder();
        if(mergerOrder.getIsScorePay() == 0 || mergerOrder.getTotalUsableScore() <= 0){
            return;
        }
        Date now = new Date();
        String userId = SecurityUtils.getUser().getUserId();
        UserExtension userExtension = userExtensionService.getOne(new LambdaQueryWrapper<UserExtension>().eq(UserExtension::getUserId, userId));
        if(userExtension.getScore() < mergerOrder.getTotalUsableScore()){
            throw new MaoshiShopBindException("积分不足无法提交订单!");
        }
        //添加积分日志
        List<com.maoshi.shop.bean.model.Order> orders = event.getOrders();
        List<UserScoreLog> logList = new ArrayList<>();
        for (com.maoshi.shop.bean.model.Order order : orders) {
            UserScoreLog userScoreLog = new UserScoreLog();
            userScoreLog.setUserId(userId);
            userScoreLog.setBizId(order.getOrderId());
            userScoreLog.setScore(order.getScore());
            userScoreLog.setSource(ScoreLogType.SCORE_CASH.value());
            userScoreLog.setCreateTime(now);
            userScoreLog.setIoType(0);
            logList.add(userScoreLog);
        }
        userScoreLogService.saveBatch(logList);
        //保存用户积分
        userExtension.setScore(userExtension.getScore() - mergerOrder.getTotalUsableScore());
        userExtensionService.updateById(userExtension);
    }

}
